package com.micro.ai.template.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.template.entity.Template;
import com.micro.ai.template.entity.TemplateStatistic;
import com.micro.ai.template.service.TemplateRatingService;
import com.micro.ai.template.service.TemplateService;
import com.micro.ai.template.service.TemplateStatisticService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 综合统计分析Controller
 *
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/analytics")
@RequiredArgsConstructor
@Tag(name = "综合统计分析", description = "系统统计分析相关接口")
public class AnalyticsController {

    private final TemplateStatisticService templateStatisticService;
    private final TemplateService templateService;
    private final TemplateRatingService templateRatingService;

    @GetMapping("/dashboard")
    @PreAuthorize("hasAuthority('analytics:query')")
    @Operation(summary = "获取仪表盘数据", description = "获取系统整体统计数据")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<Map<String, Object>> getDashboard() {
        log.info("查询仪表盘数据");
        
        Map<String, Object> dashboard = new HashMap<>();
        
        // 模板总数
        long totalTemplates = templateService.count();
        dashboard.put("totalTemplates", totalTemplates);
        
        // 今日使用统计
        LocalDate today = LocalDate.now();
        LambdaQueryWrapper<TemplateStatistic> todayWrapper = new LambdaQueryWrapper<>();
        todayWrapper.eq(TemplateStatistic::getStatDate, today);
        List<TemplateStatistic> todayStats = templateStatisticService.list(todayWrapper);
        
        int todayUseCount = todayStats.stream()
                .mapToInt(s -> s.getUseCount() != null ? s.getUseCount() : 0)
                .sum();
        int todayViewCount = todayStats.stream()
                .mapToInt(s -> s.getViewCount() != null ? s.getViewCount() : 0)
                .sum();
        
        dashboard.put("todayUseCount", todayUseCount);
        dashboard.put("todayViewCount", todayViewCount);
        
        // 总评分数
        long totalRatings = templateRatingService.count();
        dashboard.put("totalRatings", totalRatings);
        
        return ApiResponse.success(dashboard);
    }

    @GetMapping("/templates/top")
    @PreAuthorize("hasAuthority('analytics:query')")
    @Operation(summary = "热门模板排行", description = "获取最热门的模板列表")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<List<Map<String, Object>>> getTopTemplates(
            @Parameter(description = "排行榜类型") @RequestParam(defaultValue = "usage") String sortBy,
            @Parameter(description = "返回数量") @RequestParam(defaultValue = "10") int limit) {
        log.info("查询热门模板, sortBy: {}, limit: {}", sortBy, limit);
        
        // 获取所有统计数据
        List<TemplateStatistic> allStats = templateStatisticService.list();
        
        // 根据类型排序
        List<TemplateStatistic> topStats = allStats.stream()
                .sorted((s1, s2) -> {
                    switch (sortBy) {
                        case "rating":
                            return s2.getAvgRating().compareTo(s1.getAvgRating());
                        case "favorite":
                            return Integer.compare(
                                    s2.getFavoriteCount() != null ? s2.getFavoriteCount() : 0,
                                    s1.getFavoriteCount() != null ? s1.getFavoriteCount() : 0
                            );
                        case "view":
                            return Integer.compare(
                                    s2.getViewCount() != null ? s2.getViewCount() : 0,
                                    s1.getViewCount() != null ? s1.getViewCount() : 0
                            );
                        case "usage":
                        default:
                            return Integer.compare(
                                    s2.getUseCount() != null ? s2.getUseCount() : 0,
                                    s1.getUseCount() != null ? s1.getUseCount() : 0
                            );
                    }
                })
                .limit(limit)
                .collect(Collectors.toList());
        
        // 组装结果
        List<Map<String, Object>> result = new ArrayList<>();
        for (TemplateStatistic stat : topStats) {
            Template template = templateService.getById(stat.getTemplateId());
            if (template != null) {
                Map<String, Object> item = new HashMap<>();
                item.put("templateId", stat.getTemplateId());
                item.put("templateName", template.getTemplateName());
                item.put("useCount", stat.getUseCount());
                item.put("viewCount", stat.getViewCount());
                item.put("favoriteCount", stat.getFavoriteCount());
                item.put("avgRating", stat.getAvgRating());
                result.add(item);
            }
        }
        
        return ApiResponse.success(result);
    }

    @GetMapping("/templates/{templateId}/analysis")
    @PreAuthorize("hasAuthority('analytics:query')")
    @Operation(summary = "模板分析报告", description = "获取模板的详细分析报告")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "模板不存在")
    })
    public ApiResponse<Map<String, Object>> getTemplateAnalysis(
            @Parameter(description = "模板ID") @PathVariable String templateId) {
        log.info("查询模板分析报告, templateId: {}", templateId);
        
        Map<String, Object> analysis = new HashMap<>();
        
        // 基础信息
        Template template = templateService.getById(templateId);
        analysis.put("template", template);
        
        // 统计数据
        Map<String, Object> stats = templateStatisticService.getStatistics(templateId);
        analysis.put("statistics", stats);
        
        // 评分信息
        Map<String, Object> ratingInfo = templateRatingService.getAverageRating(templateId);
        analysis.put("rating", ratingInfo);
        
        // 评分分布
        Map<Integer, Long> distribution = templateRatingService.getRatingDistribution(templateId);
        analysis.put("ratingDistribution", distribution);
        
        return ApiResponse.success(analysis);
    }

    @GetMapping("/trends/daily")
    @PreAuthorize("hasAuthority('analytics:query')")
    @Operation(summary = "每日趋势", description = "获取最近N天的使用趋势")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<List<Map<String, Object>>> getDailyTrend(
            @Parameter(description = "天数") @RequestParam(defaultValue = "30") int days) {
        log.info("查询每日趋势, days: {}", days);
        
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(days);
        
        LambdaQueryWrapper<TemplateStatistic> wrapper = new LambdaQueryWrapper<>();
        wrapper.ge(TemplateStatistic::getStatDate, startDate)
                .le(TemplateStatistic::getStatDate, endDate)
                .orderByAsc(TemplateStatistic::getStatDate);
        
        List<TemplateStatistic> stats = templateStatisticService.list(wrapper);
        
        // 按日期聚合
        Map<LocalDate, List<TemplateStatistic>> dateMap = stats.stream()
                .collect(Collectors.groupingBy(TemplateStatistic::getStatDate));
        
        List<Map<String, Object>> trend = new ArrayList<>();
        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            Map<String, Object> dayData = new HashMap<>();
            dayData.put("date", date.toString());
            
            List<TemplateStatistic> dayStats = dateMap.getOrDefault(date, new ArrayList<>());
            int totalUse = dayStats.stream().mapToInt(s -> s.getUseCount() != null ? s.getUseCount() : 0).sum();
            int totalView = dayStats.stream().mapToInt(s -> s.getViewCount() != null ? s.getViewCount() : 0).sum();
            
            dayData.put("useCount", totalUse);
            dayData.put("viewCount", totalView);
            
            trend.add(dayData);
        }
        
        return ApiResponse.success(trend);
    }

    @GetMapping("/categories/stats")
    @PreAuthorize("hasAuthority('analytics:query')")
    @Operation(summary = "分类统计", description = "获取各分类的模板数量统计")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<List<Map<String, Object>>> getCategoryStats() {
        log.info("查询分类统计");
        
        // 获取所有模板
        List<Template> templates = templateService.list();
        
        // 按分类ID分组统计
        Map<String, Long> categoryCountMap = templates.stream()
                .filter(t -> t.getCategoryId() != null)
                .collect(Collectors.groupingBy(
                        t -> t.getCategoryId().toString(),
                        Collectors.counting()
                ));
        
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<String, Long> entry : categoryCountMap.entrySet()) {
            Map<String, Object> item = new HashMap<>();
            item.put("categoryId", entry.getKey());
            item.put("templateCount", entry.getValue());
            result.add(item);
        }
        
        // 按数量降序排序
        result.sort((a, b) -> Long.compare((Long) b.get("templateCount"), (Long) a.get("templateCount")));
        
        return ApiResponse.success(result);
    }

    @GetMapping("/overview")
    @PreAuthorize("hasAuthority('analytics:query')")
    @Operation(summary = "系统概览", description = "获取系统整体运行概况")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<Map<String, Object>> getSystemOverview() {
        log.info("查询系统概览");
        
        Map<String, Object> overview = new HashMap<>();
        
        // 模板相关统计
        long totalTemplates = templateService.count();
        LambdaQueryWrapper<Template> activeWrapper = new LambdaQueryWrapper<>();
        activeWrapper.eq(Template::getStatus, "published");
        long activeTemplates = templateService.count(activeWrapper);
        
        overview.put("totalTemplates", totalTemplates);
        overview.put("activeTemplates", activeTemplates);
        
        // 最近7天的数据
        LocalDate sevenDaysAgo = LocalDate.now().minusDays(7);
        LambdaQueryWrapper<TemplateStatistic> recentWrapper = new LambdaQueryWrapper<>();
        recentWrapper.ge(TemplateStatistic::getStatDate, sevenDaysAgo);
        List<TemplateStatistic> recentStats = templateStatisticService.list(recentWrapper);
        
        int recentUseCount = recentStats.stream()
                .mapToInt(s -> s.getUseCount() != null ? s.getUseCount() : 0)
                .sum();
        int recentViewCount = recentStats.stream()
                .mapToInt(s -> s.getViewCount() != null ? s.getViewCount() : 0)
                .sum();
        
        overview.put("recentUseCount", recentUseCount);
        overview.put("recentViewCount", recentViewCount);
        
        // 评分统计
        long totalRatings = templateRatingService.count();
        overview.put("totalRatings", totalRatings);
        
        return ApiResponse.success(overview);
    }
}

